package com.wswy.wzcx.widget.home;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Space;
import android.widget.TextView;
import com.blankj.utilcode.util.SizeUtils;
import com.check.ox.sdk.LionWallView;
import com.facebook.common.util.UriUtil;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.android.flexbox.AlignContent;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayout;
import com.google.android.flexbox.FlexboxLayout.DividerMode;
import com.wswy.wzcx.R;
import com.wswy.wzcx.model.home.ExtModule;
import com.wswy.wzcx.ui.other.ClickUtils;
import com.wswy.wzcx.utils.ImageUtils;
import com.wswy.wzcx.utils.StringUtils;
import com.wswy.wzcx.utils.UiUtils;
import com.wswy.wzcx.widget.OnItemClickListener;
import com.wswy.wzcx.widget.utils.ViewGroupUtils;
import java.util.List;

public class HomeCategoryLayout extends LinearLayout implements OnClickListener{

  private static final String TAG = "HomeCategoryLayout";

  public HomeCategoryLayout(Context context) {
    this(context,null);
  }

  public HomeCategoryLayout(Context context,
      @Nullable AttributeSet attrs) {
    this(context, attrs,0);
  }

  public HomeCategoryLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);


    setOrientation(VERTICAL);


    textView = new TextView(context);
    textView.setTextSize(16);
    textView.setTextColor(ContextCompat.getColor(context, R.color.textColorPrimary));
    textView.setGravity(Gravity.CENTER);
    textView.getPaint().setFakeBoldText(true);
    //textView.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(context,R.drawable.label_drawable),null,null,null);

    textView.setCompoundDrawablePadding(SizeUtils.dp2px(4));

    LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,SizeUtils.dp2px(44));
    lp.leftMargin = SizeUtils.dp2px(20);

    textView.setVisibility(GONE);
    addView(textView,lp);


    flexboxLayout = new FlexboxLayout(context);

    flexboxLayout.setFlexWrap(FlexWrap.WRAP);

    //flexboxLayout.setPadding(0,0,0,SizeUtils.dp2px(8));

    lp = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);


    addView(flexboxLayout,lp);


  }

  private TextView textView;
  private FlexboxLayout flexboxLayout;


  private int lineMaxItem = 5; //每行显示的个数
  private int maxRows = Integer.MAX_VALUE;
  private int rows=0;

  private int rowHeight = SizeUtils.dp2px(76);

//  private int maxRows = 2;

  private OnItemClickListener<ExtModule> itemDataOnItemClickListener;

  public void setLineMaxItem(int lineMaxItem) {
    this.lineMaxItem = lineMaxItem;
  }

  public void showHorizontalDivider(Drawable drawable){
    flexboxLayout.setDividerDrawableHorizontal(drawable);
  }

  public void showVerticalDivider(Drawable drawable){
    flexboxLayout.setDividerDrawableVertical(drawable);
  }

  public void showDivider(@DividerMode int dividerMode){
    flexboxLayout.setShowDivider(dividerMode);
  }

  public void setRowHeight(int rowHeight){
    this.rowHeight = rowHeight;
  }

  public void showCategory(List<ExtModule> data){
    textView.setVisibility(GONE);
    //textView.setText(title);
    readerItems(data);
  }

  public void updateSignByTag(String tag,String signStr){
    int childCount = flexboxLayout.getChildCount();

    for (int i = 0; i < childCount; i++) {
      View inflate = flexboxLayout.getChildAt(i);

      if(inflate != null && inflate.getTag() instanceof ExtModule && TextUtils.equals(((ExtModule) inflate.getTag()).targetUrl,tag)){

        SimpleDraweeView imageView = inflate.findViewById(R.id.img_icon);

        TextView sign = inflate.findViewById(R.id.img_sign);

        updateSign(sign,imageView,signStr,true);

        break;
      }
    }
  }

  public void updateNumByTag(String tag,int num){
    int childCount = flexboxLayout.getChildCount();

    for (int i = 0; i < childCount; i++) {
      View inflate = flexboxLayout.getChildAt(i);

      if(inflate != null && inflate.getTag() instanceof ExtModule && TextUtils.equals(((ExtModule) inflate.getTag()).targetUrl,tag)){
        updateNum(inflate,num);
        break;
      }
    }
  }

  public void showCategory(String title,List<ExtModule> data){
    textView.setVisibility(VISIBLE);
    textView.setText(title);

    readerItems(data);
  }

  public void setOnItemClickListener(
      OnItemClickListener<ExtModule> itemDataOnItemClickListener) {
    this.itemDataOnItemClickListener = itemDataOnItemClickListener;
  }

  private void readerItems(List<ExtModule> datas){

    flexboxLayout.removeAllViewsInLayout();

    flexboxLayout.setAlignContent(AlignContent.FLEX_START);
    int idx = 0;

    int r = 1;

    for (ExtModule data : datas) {
      View inflate = LayoutInflater.from(getContext())
          .inflate(R.layout.layout_home_category_item, this, false);

      FlexboxLayout.LayoutParams lp = new FlexboxLayout.LayoutParams(0,rowHeight);

      lp.setFlexGrow(1);

      if (idx> 0 && idx % lineMaxItem == 0){
        lp.setWrapBefore(true);
        r++;
      }

      idx++;

      bindData(inflate,data);

      inflate.setTag(data);

      inflate.setOnClickListener(this);

      flexboxLayout.addView(inflate,lp);

      if (idx / lineMaxItem >= maxRows){
        return;
      }
    }

    //剩余的空白补充
    int remain = idx % lineMaxItem;

    if (remain > 0){
      FlexboxLayout.LayoutParams lp = new FlexboxLayout.LayoutParams(0,rowHeight);

      lp.setFlexGrow(lineMaxItem - remain);
      flexboxLayout.addView(new Space(getContext()),lp);
    }

    rows = r;

  }


  private void bindData(View inflate,ExtModule module){
     SimpleDraweeView imageView = inflate.findViewById(R.id.img_icon);
    TextView textView = inflate.findViewById(R.id.tv_name);

    final TextView sign = inflate.findViewById(R.id.img_sign);

    if (module.isTuiaAD()){
      //推啊广告
      LionWallView ad = createAD();
      //改小位置并透明
      ((ViewGroup) inflate).addView(ad,0,new ViewGroup.LayoutParams(30,30));

      ad.loadAd(module.getTuaiAdId());
    }

    String signTag = !TextUtils.isEmpty(module.tag)?module.tag:module.dSign;

    updateSign(sign,imageView,signTag,false);

    ImageUtils.showImage(imageView,module.image);

    textView.setText(module.title);

  }


  private void updateSign(final TextView sign,final ImageView imageView,final String signTag,boolean cBg){

    if (!TextUtils.isEmpty(signTag)) {
      sign.setVisibility(INVISIBLE);

      //特殊处理
      if ("dot".equalsIgnoreCase(signTag)){
        sign.setBackground(null);
        sign.setCompoundDrawablesWithIntrinsicBounds(R.drawable.sign_dot,0,0,0);
        sign.setText(null);
      }else {
        if (cBg){
          int dp2 = SizeUtils.dp2px(2);
          int dp6 = SizeUtils.dp2px(6);
          sign.setPadding(dp6,dp2,dp6,dp2);
          sign.setBackgroundResource(R.drawable.shape_bg_9);
        }else {
          sign.setBackgroundResource(R.drawable.home_item_sign);
        }
        sign.setCompoundDrawablesWithIntrinsicBounds(0,0,0,0);
        sign.setText(signTag);
      }


      UiUtils.INSTANCE.addOnGlobalLayoutListener(sign, new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {

          //改善角标位置
          int max = ((View) imageView.getParent()).getWidth();
          int dp4 = SizeUtils.dp2px(4);
          int fw = imageView.getRight()- dp4 + sign.getWidth();

          int topM = imageView.getTop()-sign.getHeight()/2;

          MarginLayoutParams layoutParams = (MarginLayoutParams) sign.getLayoutParams();
          if (fw > max){
            layoutParams.leftMargin = max - sign.getWidth() - dp4;
          }else {
            layoutParams.leftMargin = imageView.getRight() - dp4;
          }

          if (topM >0){
            layoutParams.topMargin = topM;
          }

          if ("dot".equalsIgnoreCase(signTag)){
            //如果是圆点 特殊处理
            layoutParams.leftMargin = imageView.getRight()-sign.getWidth()/2;
          }

          sign.setLayoutParams(layoutParams);
          sign.post(new Runnable() {
            @Override
            public void run() {
              sign.setVisibility(VISIBLE);
            }
          });
        }
      });

    } else {
      sign.setVisibility(INVISIBLE);
    }
  }

  private void updateNum(View container,int num){
    if (container instanceof ConstraintLayout){
      View imgView = container.findViewById(R.id.img_icon);



    }


  }

  public int getRow(){
    return rows;
  }

  @Override
  public void onClick(View v) {
    if (ClickUtils.isFastClick()){
      return;
    }

    if(itemDataOnItemClickListener != null){
      Object tag = v.getTag();
      if(tag instanceof ExtModule){
        final View sign = v.findViewById(R.id.img_sign);
        if (sign != null){
          postDelayed(new Runnable() {
            @Override
            public void run() {
              sign.setVisibility(GONE);
            }
          },500);
        }
        itemDataOnItemClickListener.onItemClick(v, ((ExtModule) tag));
      }
    }

  }


  private Uri parseImage(String image){
    if(TextUtils.isEmpty(image)){
      return null;
    }
    if(image.startsWith("http")){
      return UriUtil.parseUriOrNull(image);
    }
    return StringUtils.getUriForAssets(image);
  }



  private LionWallView createAD(){
    return (LionWallView) LayoutInflater.from(getContext()).inflate(R.layout.ad_home_module,null,false);
  }

}
